/**
 * Created by xiaoz on 16/8/13.
 */
define(["utils", "base", "../comPersonSelector/leftTree"], function (utils, baseClass, leftTree) {


    function DepartResultItem(config) {
        var _this = this;
        this.itemData = config.itemData;
        if (!this.itemData.teamId) {
            this.itemData.teamId = this.itemData.deptId;
        }
        this.selector = config.selector;
        this.parent = config.parent;
        this.$el = $("<div class='dc-ps-person-item'></div>");
        var imgWrap = $("<div class='dc-ps-depart-icon'></div>");
        var nameSpan = $("<span class='dc-ps-person-name' title='"+this.itemData.name+"'>" + this.itemData.name + "</span>");
        var closeBtn = $("<span class='dc-ps-item-close'></span>");
        closeBtn.bind("click", function (e) {
            _this.parent.deleteDepart(_this);
        });
        this.$el.append(imgWrap).append(nameSpan).append(closeBtn);
    }

    function TeamResultItem(config) {
        var _this = this;
        this.itemData = config.itemData;
        if (!this.itemData.teamId) {
            this.itemData.teamId = this.itemData.id;
        }
        this.selector = config.selector;
        this.parent = config.parent;
        this.$el = $("<div class='dc-ps-person-item'></div>");
        var imgWrap = $("<div class='dc-ps-depart-icon dc-ps-team-icon'></div>");
        var nameSpan = $("<span class='dc-ps-person-name' title='"+this.itemData.name +"'>" + this.itemData.name + "</span>");
        var closeBtn = $("<span class='dc-ps-item-close'></span>");
        closeBtn.bind("click", function (e) {
            _this.parent.deleteTeamFromRight(_this);
        });
        this.$el.append(imgWrap).append(nameSpan).append(closeBtn);
    }

    function ResultItem(config) {
        var _this = this;
        this.parent = config.parent;
        this.itemData = config.itemData;
        this.selector = config.selector;
        this.$el = $("<div class='dc-ps-person-item'></div>");
        var imgWrap = $("<div class='dc-ps-person-avatar'></div>");
        var nameSpan = $("<span class='dc-ps-person-name' title='"+this.itemData.name+"'>" + this.itemData.name + "</span>");
        var img = new Image();
        img.src = this.itemData.avatar;
        img.onerror = function () {
            img.src = "./imgs/header.png";
        }
        imgWrap.append(img);
        var closeBtn = $("<span class='dc-ps-item-close'></span>");
        closeBtn.bind("click", function (e) {
            _this.parent.deletePersonFromRight(_this);
        });
        this.$el.append(imgWrap).append(nameSpan).append(closeBtn);
    }

    function SelectedResultWrap(config) {
        this.selector = config.selector;
        this.$el = $("<div></div>");
        this.departWrap = $("<div></div>");
        this.personWrap = $("<div></div>");
        this.$el.append(this.departWrap).append(this.personWrap);
    }

    SelectedResultWrap.prototype = {
        reset: function () {
            this.departWrap.empty();
            this.personWrap.empty();
            this.selectedPersonItemDict = {};
            this.selectedTeamItemDict = {};
        },

        addPerson: function (data) {
            var item = new ResultItem({
                selector: this.selector,
                itemData: data,
                parent: this,
                type: "person"
            });
            this.selectedPersonItemDict[data.memberId.toString()] = item;
            this.personWrap.append(item.$el);
        },
        deletePersonFromRight: function (itemInstance) {
            var memberId = itemInstance.itemData.memberId.toString();
            for (var i = 0, j = this.selector.selectedData.length; i < j; i++) {
                var itemData = this.selector.selectedData[i];
                if (itemData.dataType === 4) {
                    if (itemData.memberId.toString() === memberId) {
                        this.selector.selectedData.splice(i, 1);
                        break;
                    }
                }
            }
            itemInstance.$el.remove();
            this.selector.personList.unChecked(memberId);
        },
        deleteTeamFromRight: function (itemInstance) {
            var teamId = itemInstance.itemData.teamId.toString();
            for (var i = 0, j = this.selector.selectedData.length; i < j; i++) {
                var itemData = this.selector.selectedData[i];
                if (itemData.dataType === 3) {
                    if (itemData.teamId.toString() === teamId) {
                        this.selector.selectedData.splice(i, 1);
                        break;
                    }
                }
            }
            itemInstance.$el.remove();
            this.selector.teamList.unChecked(teamId);
        },
        deletePerson: function (memberId) {
            var item = this.selectedPersonItemDict[memberId.toString()];
            if (item) {
                item.$el.remove();
            }
        },
        deleteDepart: function (departItemInstance) {
            var deptId = departItemInstance.itemData.teamId.toString();
            for (var i = 0, j = this.selector.selectedData.length; i < j; i++) {
                var itemData = this.selector.selectedData[i];
                if (itemData.dataType === 1) {
                    if (itemData.teamId.toString() === deptId) {
                        this.selector.selectedData.splice(i, 1);
                        break;
                    }
                }
            }
            departItemInstance.$el.remove();
            this.selector.rebindSelectedDepart();
        },
        addTeam: function (data) {
            var item = new TeamResultItem({
                selector: this.selector,
                itemData: data,
                parent: this,
                type: "person"
            });
            this.selectedTeamItemDict[data.teamId.toString()] = item;
            this.personWrap.append(item.$el);
        },
        deleteTeam: function (teamID) {
            var item = this.selectedTeamItemDict[teamID.toString()];
            if (item) {
                item.$el.remove();
            }
        },
        addDeparts: function (dataArr) {
            this.departWrap.empty();

            for (var i = 0, j = dataArr.length; i < j; i++) {
                var item = new DepartResultItem({
                    selector: this.selector,
                    itemData: dataArr[i],
                    parent: this
                });
                this.departWrap.append(item.$el);

            }

        }
    }


    function PersonItem(config) {
        var _this = this;
        this.itemData = config.itemData;
        this.selector = config.selector;
        this.$el = $("<div class='dc-ps-person-item'></div>");
        var imgWrap = $("<div class='dc-ps-person-avatar'></div>");
        var nameSpan;
        var departname= _this.itemData.deptName?_this.itemData.deptName:"";
        if (this.itemData.deptName && config.fromSearch == 1) {
            nameSpan=$("<div class='dc-ps-person-name' style='line-height: 18px'><div >" + _this.itemData.userName + "</div><span class='dc-ps-person-departname'>" + _this.itemData.deptName + "</span></div>");
        } else if (this.itemData.deptName && config.fromSearch == 0) {
            // _this.$hoverEl = $("<div class='person-selector-item-hover'><div class='person-selector-item-up'></div><div >" + _this.itemData.deptName + " > " + _this.itemData.userName + "</div></div>");
            // this.$el.hover(function (e) {
            //     _this.$hoverEl.css({'display': 'block'});
            // }, function (e) {
            //     _this.$hoverEl.css({'display': 'none'});
            // });
            nameSpan = $("<div class='dc-ps-person-name'><div style='line-height:18px'>" + this.itemData.userName + "<br/><span class='dc-ps-person-departname'>"+departname+"</span></div>" + "</div>");
        } else {
            nameSpan = $("<div class='dc-ps-person-name'><div style='line-height:18px'>" + this.itemData.userName + "<br/><span class='dc-ps-person-departname'>"+departname+"</span></div>" + "</div>");
        }
        var img = new Image();
        img.src = this.itemData.headImgUrl;
        img.onerror = function () {
            img.src = "./imgs/header.png";
        }
        imgWrap.append(img);
        this.memberId = this.itemData.memberId.toString();
        this.isSelected = false;
        this.checkbox = $("<span class='person-selector-checkbox yy-fontawesome dc-ps-person-checkbox'></span>");

        var index = this.curIsSelected();
        if (index >= 0) {
            this.checkbox.addClass("checked");
        }

        this.$el.append(imgWrap).append(nameSpan).append(this.checkbox).append(this.$hoverEl);
        this.$el.bind("click", function (e) {
            var cIndex = _this.curIsSelected();
            //this.resultWrap
            if (cIndex >= 0) {
                _this.checkbox.removeClass("checked");
                _this.selector.resultWrap.deletePerson(_this.itemData.memberId);
                _this.selector.selectedData.splice(cIndex, 1);
            } else {
                _this.checkbox.addClass("checked");
                var sData = {
                    "id": null,
                    "templateId": null,
                    "userId": null,
                    "userName": _this.itemData.userName,
                    "memberId": _this.itemData.memberId,
                    "spaceId": _this.itemData.szId,
                    "spaceName": null,
                    "teamId": 0,
                    "teamName": null,
                    "createTime": 1479889596000,
                    "dataType": 4,
                    "avatar": _this.itemData.headImgUrl,
                    "person": true,
                    "dept": false,
                    "name": _this.itemData.userName
                };
                _this.selector.resultWrap.addPerson(sData);
                _this.selector.selectedData.push(sData);
            }
        });
    }

    PersonItem.prototype = {
        unChecked: function () {
            this.checkbox.removeClass("checked");
        },
        curIsSelected: function () {
            // [
            //     {
            //         "id": 109,
            //         "templateId": 130,
            //         "userId": 0,
            //         "userName": null,
            //         "memberId": 0,
            //         "spaceId": 86114,
            //         "spaceName": null,
            //         "teamId": 60353,
            //         "teamName": "事业部",
            //         "createTime": 1479889596000,
            //         "dataType": 1,
            //         "avatar": null,
            //         "person": false,
            //         "dept": true,
            //         "name": "事业部"
            //     },
            //     {
            //         "id": 110,
            //         "templateId": 130,
            //         "userId": 95,
            //         "userName": "安明明",
            //         "memberId": 383080,
            //         "spaceId": 86114,
            //         "spaceName": null,
            //         "teamId": 0,
            //         "teamName": null,
            //         "createTime": 1479889596000,
            //         "dataType": 4,
            //         "avatar": "http://staticoss.upesn.com/15015/383080/201603/9/1457509139ee1m.jpg",
            //         "person": true,
            //         "dept": false,
            //         "name": "安明明"
            //     }
            // ]
            var _this = this;
            var re = -1;
            for (var i = 0, j = _this.selector.selectedData.length; i < j; i++) {
                if (_this.selector.selectedData[i].dataType !== 4) {
                    continue;
                }
                if (_this.selector.selectedData[i].memberId.toString() === _this.memberId.toString()) {
                    re = i;
                    break;
                }
            }
            return re;
        }
    }


    function TeamItem(config) {
        var _this = this;

        this.itemData = {
            "id": config.itemData.id,
            "templateId": null,
            "userId": null,
            "userName": null,
            "memberId": null,
            "spaceId": null,
            "spaceName": null,
            "teamId": config.itemData.id,
            "teamName": config.itemData.groupName,
            "createTime": 1479889596000,
            "dataType": 3,
            "avatar": null,
            "person": true,
            "dept": false,
            "name": config.itemData.groupName
        };
        this.selector = config.selector;
        this.$el = $("<div class='dc-ps-person-item'></div>");
        var imgWrap = $("<div class='dc-ps-team-avatar'></div>");
        var nameSpan = $("<span class='dc-ps-person-name'>" + this.itemData.teamName + "</span>");
        this.teamId = this.itemData.teamId.toString();
        this.isSelected = false;
        this.checkbox = $("<span class='person-selector-checkbox yy-fontawesome dc-ps-person-checkbox'></span>");

        var index = this.curIsSelected();
        if (index >= 0) {
            this.checkbox.addClass("checked");
        }

        this.$el.append(imgWrap).append(nameSpan).append(this.checkbox);
        this.$el.bind("click", function (e) {
            var cIndex = _this.curIsSelected();
            //this.resultWrap
            if (cIndex >= 0) {
                _this.checkbox.removeClass("checked");
                _this.selector.resultWrap.deleteTeam(_this.itemData.teamId);
                _this.selector.selectedData.splice(cIndex, 1);
            } else {
                _this.checkbox.addClass("checked");
                _this.selector.resultWrap.addTeam(_this.itemData);
                _this.selector.selectedData.push(_this.itemData);
            }
        });
    }

    TeamItem.prototype = {
        unChecked: function () {
            this.checkbox.removeClass("checked");
        },
        checked: function () {
            this.checkbox.addClass("checked");
        },
        curIsSelected: function () {
            var _this = this;
            var re = -1;
            for (var i = 0, j = _this.selector.selectedData.length; i < j; i++) {
                if (_this.selector.selectedData[i].dataType !== 3) {
                    continue;
                }
                if (_this.selector.selectedData[i].teamId.toString() === _this.teamId.toString()) {
                    re = i;
                    break;
                }
            }
            return re;
        }
    }


    function TeamList(config) {
        this.pageview = config.pageview;
        this.selector = config.selector;
        this.$el = $("<div></div>");
        this.items = [];
    }

    TeamList.prototype = {

        unChecked: function (teamid) {
            for (var i = 0, j = this.items.length; i < j; i++) {
                var itemData = this.items[i].itemData;
                if (teamid === itemData.teamId.toString()) {
                    this.items[i].unChecked();
                }
            }
        },
        showNoData: function () {
            this.noData = $("<div class='dc-ps-nodata'>您还未加入任何团队</div>");
            this.$el.append(this.noData);
        },

        initItems: function (arr) {
            if (arr.length === 0) {
                this.showNoData();
            } else {
                for (var i = 0, j = arr.length; i < j; i++) {
                    var tl = new TeamItem({itemData: arr[i], selector: this.selector});
                    this.$el.append(tl.$el);
                    this.items.push(tl);
                }
                this.setSelected();

            }
        },
        setSelected: function () {
            for (var n = 0, m = this.items.length; n < m; n++) {
                this.items[n].unChecked();
            }
            for (var i = 0, j = this.selector.selectedData.length; i < j; i++) {
                var itemData = this.selector.selectedData[i];
                if (itemData.dataType !== 3) {
                    continue;
                }

                for (var ii = 0, jj = this.items.length; ii < jj; ii++) {
                    var it = this.items[ii];

                    if (itemData.teamId.toString() === it.itemData.teamId.toString()) {
                        it.checked();
                    }

                }

            }
        },
        showLoading: function () {
            if (this.reloadWrap) {
                this.reloadWrap.addClass("displaynone");
            }
            if (!this.errorWrap) {
                this.errorWrap = $("<div class='dc-ps-team-loading displaynone'></div>");
                this.errorWrap.spin('tiny', '#999');
                this.$el.append(this.errorWrap);
            }
            this.errorWrap.removeClass("displaynone");
        },
        showError: function () {
            var _this = this;
            if (!this.reloadWrap) {
                this.reloadWrap = $("<div class='dc-ps-team-reload displaynone'>网络异常！<span> 点击重新加载</span></div>");
                this.$el.append(this.reloadWrap);
                this.reloadWrap.bind("click", function () {
                    _this.loadData();
                });
            }
            this.reloadWrap.removeClass("displaynone");
        },
        loadData: function () {
            var _this = this;
            this.showLoading();
            this.pageview.ajax({
                type: "GET",
                url: "/group/me",
                timeout: 9000,
                data: {},
                success: function (data) {
                    _this.errorWrap.addClass("displaynone");
                    if (data.code === 0) {
                        _this.initItems(data.data);
                    } else {
                        _this.showError();
                    }
                },
                error: function (e) {
                    _this.errorWrap.addClass("displaynone");
                    _this.showError();
                }
            });
        }
    };

    function PersonList(config) {
        this.pageSize = 40;
        this.selector = config.selector;
        this.items = [];
        this.itemsData = [];

        this.selector.selectedPersonData = this.selector.selectedPersonData || [];
        this.pageview = this.selector.pageview;
        this.$el = $("<div class='dc-ps-listout'></div>");
        this.listWrap = $("<div></div>");
        this.$el.append(this.listWrap);
    }


    PersonList.prototype.loadNextPageData = function () {
        var _this = this;

        this.pageNum += 1;
        this.loadData({
            success: function (data,fromSearch) {
                _this.bindPersonData(data,fromSearch);
            }, error: function () {
                _this.pageNum -= 1;
            }
        });
    };

    PersonList.prototype.empty = function () {
        for (var i = this.items.length - 1; i >= 0; i--) {
            this.items[i].$el.remove();
        }
        this.items = [];
    };

    PersonList.prototype.loadData = function (params) {
        var _this =this;
        this.showLoadPersonLoading();
        this.pageview.ajax({
            type: "GET",
            url: "/team/getUsers",
            data: {
                pageSize: this.pageSize,
                pageNumber: this.pageNum,
                keyWord: this.keyWord || ""
            },
            success: function (data) {
                if (data.code === 0) {
                    params.success(data.data,_this.keyWord?1:0);
                } else {
                    params.error();
                }
            },
            error: function (e) {
                params.error();
            }
        });
    };


    PersonList.prototype.reload = function () {
        var _this = this;
        this.loadData({
            success: function (data,fromSearch) {
                _this.bindPersonData(data,fromSearch);
            }, error: function () {
                _this.pageNum -= 1;
            }
        });
    };

    PersonList.prototype.loadFirstPageData = function (str, succCallBack, errorCallback) {
        this.keyWord = str;
        var _this = this;
        this.listWrap.empty();
        this.empty();


        this.pageNum = 1;

        this.loadData({
            success: function (data,fromSearch) {
                _this.bindPersonData(data,fromSearch);
                succCallBack && succCallBack();
            }, error: function () {
                errorCallback && errorCallback();
                _this.pageNum = 1;
            }
        });

    };

    PersonList.prototype.bindPersonData = function (data,fromSearch) {
        if (this.pageNum === 1) {
            this.items = [];
            this.itemsData = [];
        }
        for (var i = 0, j = data.length; i < j; i++) {
            var item = new PersonItem({
                itemData: data[i],
                selector: this.selector,
                fromSearch: fromSearch
            });
            this.items.push(item);
            this.itemsData.push(data[i]);
            this.listWrap.append(item.$el);
        }
        if (data.length < this.pageSize) {
            this.showLoadDone();
        } else {
            this.showCanLoadMorePerson();
        }
    };

    PersonList.prototype.setSelected = function () {
        if (this.itemsData.length > 0) {
            this.listWrap.empty();
            this.bindPersonData(this.itemsData,0);
        }

    };


    PersonList.prototype.unChecked = function (memberId) {
        for (var i = 0, j = this.items.length; i < j; i++) {
            var itemData = this.items[i].itemData;
            if (memberId === itemData.memberId.toString()) {
                this.items[i].unChecked();
            }
        }
    };
    PersonList.prototype.showLoadDone = function () {
        var _this = this;
        this.showLoadPersonLoadingErrorWrap && this.showLoadPersonLoadingErrorWrap.addClass("displaynone");
        this.showLoadPersonLoadingWrap && this.showLoadPersonLoadingWrap.addClass("displaynone");
        this.loadMoreBtn && this.loadMoreBtn.addClass("displaynone");
        if (!this.hadloadDone) {
            this.hadloadDone = $("<div class='ds-ps-loadperson-loaddone displaynone'>已加载全部</div>");

            this.$el.append(this.hadloadDone);
        }
        this.hadloadDone.removeClass("displaynone");
    };


    PersonList.prototype.showCanLoadMorePerson = function () {
        var _this = this;
        this.showLoadPersonLoadingErrorWrap && this.showLoadPersonLoadingErrorWrap.addClass("displaynone");
        this.showLoadPersonLoadingWrap && this.showLoadPersonLoadingWrap.addClass("displaynone");
        if (!this.loadMoreBtn) {
            this.loadMoreBtn = $("<div class='ds-ps-loadperson-loadmore displaynone'>点击加载更多</div>");
            this.loadMoreBtn.bind("click", function (e) {
                _this.loadNextPageData();
            });
            this.$el.append(this.loadMoreBtn);
        }
        this.loadMoreBtn.removeClass("displaynone");
    };

    PersonList.prototype.showLoadPersonLoadingError = function () {
        var _this = this;
        this.showLoadPersonLoadingWrap && this.showLoadPersonLoadingWrap.addClass("displaynone");
        this.loadMoreBtn && this.loadMoreBtn.addClass("displaynone");
        this.hadloadDone && this.hadloadDone.addClass("displaynone");
        if (!this.showLoadPersonLoadingErrorWrap) {
            this.showLoadPersonLoadingErrorWrap = $("<div class='ds-ps-loadperson-loadingerror displaynone'>网络错误,<span>重新加载</span></div>");
            this.showLoadPersonLoadingErrorWrap.bind("click", function (e) {
                _this.reload();
            });
            this.$el.append(this.showLoadPersonLoadingErrorWrap);
        }
        this.showLoadPersonLoadingErrorWrap.removeClass("displaynone");
    };

    PersonList.prototype.showLoadPersonLoading = function () {
        this.loadMoreBtn && this.loadMoreBtn.addClass("displaynone");
        this.hadloadDone && this.hadloadDone.addClass("displaynone");
        this.showLoadPersonLoadingErrorWrap && this.showLoadPersonLoadingErrorWrap.addClass("displaynone");
        if (!this.showLoadPersonLoadingWrap) {
            this.showLoadPersonLoadingWrap = $("<div class='ds-ps-loadperson-loading displaynone'></div>");
            var loadIcon = $("<div class='ds-loading-icon'></div>");
            loadIcon.spin('tiny', '#999');
            var loadLabel = $("<span class='ds-loading-label'>正在加载</span>");
            this.showLoadPersonLoadingWrap.append(loadIcon).append(loadLabel);
            this.$el.append(this.showLoadPersonLoadingWrap);
        }
        this.showLoadPersonLoadingWrap.removeClass("displaynone");
    };

    var Component = function (config) {
        var _this = this;
        Component.baseConstructor.call(this, config);
        this.isInit = true;
        this.isInitTeam = true;
        var okMethodName = config.comKey + "_ok";
        this.okMethod = this.pageview.plugin[okMethodName];

        this.leftGroups = {};

        this.initLayout();
    };

    utils.extendClass(Component, baseClass);

    Component.prototype.initLayout = function () {
        var _this = this;
        var title = this.config.title || "选择可见范围";
        this.bk = $("<div class='dc-ps-bk displaynone'></div>");
        this.outWrap = $("<div class='ds-ps-outwrap displaynone'></div>");
        var dialog = $("<div class='ds-ps-dialog'></div>");
        var header = $("<div class='ds-ps-header'></div>");
        var title = $("<span class='ds-ps-header-title'>" + title + "</span>");
        this.title = title;
        var close = $("<div class='ds-ps-header-close'></div>");
        close.bind("click", function () {
            _this.hide();
        });
        header.append(title).append(close);
        var body = $("<div class='ds-ps-body'></div>");
        this.bodyLeft = $("<div class='ds-ps-body-left'></div>");
        this.initBodyLeft();
        this.bodyRight = $("<div class='ds-ps-body-right'></div>");
        this.initBodyRight();
        body.append(this.bodyLeft).append(this.bodyRight);
        var footer = $("<div class='ds-ps-footer'></div>");
        var mes = this.config.mes || "每次选择不可超过500人，请分批选择";
        var footer_span = $("<span class='ds-ps-label'>" + mes + "</span>");
        var cancel_btn = $("<button class='ds-ps-cancelbtn'>取消</button>");
        cancel_btn.bind("click", function () {
            _this.hide();
        });
        var ok_btn = $("<button class='ds-ps-okbtn'>确定</button>");
        ok_btn.bind("click", function () {
            _this.getResult();
        });
        footer.append(footer_span).append(ok_btn).append(cancel_btn);
        dialog.append(header).append(body).append(footer);
        var midspan = $("<span class='ds-ps-midspan'></span>");
        this.outWrap.append(dialog).append(midspan);
        this.pageview.$el.append(this.bk).append(this.outWrap);


        this.selectedPersonIdArr = [];

    };

    Component.prototype.initBodyRight = function () {
        this.resultWrap = new SelectedResultWrap({
            selector: this
        });
        this.bodyRight.append(this.resultWrap.$el);
    };


    Component.prototype.initBodyLeft = function () {
        var _this = this;
        var mod = this.config.mod ? this.config.mod : 0;  //mod为3时仅显示成员

        var leftMid = $("<div class='ds-ps-leftmid'></div>");

        var segmentItemWrap = $("<div class='dp-ps-segment-wrap'></div>");
        this.departSegmentItem = $("<div class='dp-ps-segment-label dp-ps-segment-label-selected'>部门</div>");
        this.curSegmentItem = this.departSegmentItem;
        segmentItemWrap.bind("click", function () {
            _this.segementChange(_this.departSegmentItem, 0);
        });
        segmentItemWrap.append(this.departSegmentItem);

        var segmentItemWrap1 = $("<div  class='dp-ps-segment-wrap'></div>");
        this.teamSegmentItem = $("<div class='dp-ps-segment-label'>团队</div>");
        segmentItemWrap1.bind("click", function () {
            _this.segementChange(_this.teamSegmentItem, 1);
        });
        segmentItemWrap1.append(this.teamSegmentItem);


        var segmentItemWrap2 = $("<div class='dp-ps-segment-wrap'></div>");
        this.personSegmentItem = $("<div class='dp-ps-segment-label'>成员</div>");
        segmentItemWrap2.bind("click", function () {
            _this.segementChange(_this.personSegmentItem, 2);
        });
        segmentItemWrap2.append(this.personSegmentItem);

        leftMid.append(segmentItemWrap).append(segmentItemWrap1).append(segmentItemWrap2);

        var leftBottom = $("<div class='ds-ps-leftbottom'></div>");
        this.initViewPagers(leftBottom);
        this.bodyLeft.append(leftMid).append(leftBottom);

        if (mod === 3) {
            //只显示成员
            leftMid.addClass("displaynone");
            leftBottom.css({"top": "0px"});
        }
    };

    Component.prototype.segementChange = function (target, index) {
        if (this.curSegmentItem) {
            this.curSegmentItem.removeClass("dp-ps-segment-label-selected");
        }
        this.curSegmentItem = target;
        this.curSegmentItem.addClass("dp-ps-segment-label-selected");
        if (index === 2) {
            this.departWrap.addClass("displaynone");
            this.personWrap.removeClass("displaynone");
            this.teamWrap.addClass("displaynone");
            if (this.isInit === true) {
                this.personList.loadFirstPageData("");
                this.isInit = false;
            }
        } else if (index === 0) {
            this.departWrap.removeClass("displaynone");
            this.teamWrap.addClass("displaynone");
            this.personWrap.addClass("displaynone");
        } else {
            this.departWrap.addClass("displaynone");
            this.teamWrap.removeClass("displaynone");
            this.personWrap.addClass("displaynone");
            if (this.isInitTeam === true) {
                this.teamList.loadData()
                this.isInitTeam = false;
            }
        }
    };

    Component.prototype.getResult = function () {
        this.okMethod.call(this.pageview.plugin, this);
    };
    Component.prototype.selectedChange = function (headerItemInstance) {
        this.deptResult = {};
        for (var i = this.selectedData.length - 1; i >= 0; i--) {
            var itemdata = this.selectedData[i];
            if (itemdata.dataType === 1) {
                this.selectedData.splice(i, 1);
            }
        }
        var Re = [];
        var departArr = this.leftTree.getResult().dept;
        for (var ii = 0, jj = departArr.length; ii < jj; ii++) {
            var dData = departArr[ii];
            Re.push({
                "id": null,
                "templateId": null,
                "userId": null,
                "userName": null,
                "memberId": null,
                "spaceId": null,
                "spaceName": null,
                "teamId": dData.deptId,
                "teamName": dData.name,
                "createTime": null,
                "dataType": 1,
                "avatar": null,
                "person": false,
                "dept": true,
                "name": dData.name
            });
        }
        this.selectedData = this.selectedData.concat(Re);

        this.resultWrap.addDeparts(Re);
    };

    Component.prototype.rebindSelectedDepart = function () {
        this.leftTree.clearSelected();
        var selectedDepart = [];
        for (var i = 0, j = this.selectedData.length; i < j; i++) {
            var itemData = this.selectedData[i];
            if (itemData.dataType !== 1) {
                continue;
            }
            var detpID = itemData.teamId;
            selectedDepart.push(itemData);
            var selectedGroup = this.leftGroups[detpID];
            if (selectedGroup) {
                selectedGroup.checkAllChildren();
                selectedGroup.setParentGroupIndeterminate();
            }
        }
        return selectedDepart;
    };

    Component.prototype.setSelected = function (data) {
        this.selectedData = utils.copy(data || []);
        this.leftTree.clearSelected();
        this.resultWrap.reset();
        var selectedDepart = [];
        for (var i = 0, j = this.selectedData.length; i < j; i++) {
            var itemData = this.selectedData[i];
            if (itemData.dataType === 4) {
                this.resultWrap.addPerson(itemData);
                continue;
            }
            if (itemData.dataType === 3) {
                this.resultWrap.addTeam(itemData);
                continue;
            }
            if (itemData.dataType !== 1) {
                continue;
            }
            var detpID = itemData.teamId;
            selectedDepart.push(itemData);
            var selectedGroup = this.leftGroups[detpID];
            if (selectedGroup) {
                selectedGroup.checkAllChildren();
                selectedGroup.setParentGroupIndeterminate();
            }
        }
        this.personList.setSelected();
        this.teamList.setSelected();

        this.resultWrap.addDeparts(selectedDepart);

    };


    Component.prototype.getDepartData = function () {
        var _this = this;
        this.departWrapLoading.removeClass("displaynone");

        this.pageview.ajax({
            type: "GET",
            url: "/team/getDepts",
            data: {},
            success: function (data) {
                if (data.code === 0) {
                    _this.DeptDictData = {};
                    var dataArr = data.data;
                    if (dataArr.length === 0) {
                        _this.noData = $("<div class='dc-ps-nodata' style=' position:absolute;left:150px;top:15px; '>暂无部门信息</div>");
                        _this.departWrap.append(_this.noData);
                    }
                    for (var i = 0, j = dataArr.length; i < j; i++) {
                        var itemData = dataArr[i];
                        itemData.deptName = itemData.name;
                        itemData.deptId = itemData.id;
                        var pid = itemData.pid.toString();
                        if (!_this.DeptDictData[pid]) {
                            _this.DeptDictData[pid] = [];
                        }
                        _this.DeptDictData[pid].push({value: itemData});
                    }
                    // _this.DeptDictData = {0:[{value:{deptName:"1",deptId:1}},{value:{deptName:"12",deptId:2}}],"1":[
                    //   {value:{deptName:"13",deptId:4}},  {value:{deptName:"123",deptId:5}}
                    // ]};
                    _this.leftGroups = {};
                    _this.leftTree.init(_this.DeptDictData);

                    // _this.setSelectedData({0:[{value:{deptName:"1",deptId:1}}]});
                    _this.departWrapLoading.addClass("displaynone");
                } else {
                    _this.showLoadDeptError();
                }
            },
            error: function (e) {
                _this.showLoadDeptError();
            }
        });


    };

    Component.prototype.showLoadDeptError = function () {
        var _this = this;
        this.departWrapLoading.addClass("displaynone");
        if (!this.loadDeptError) {
            this.loadDeptError = $("<div class='dp-ps-vp-dept-loadingerror displaynone'>网络错误,<span>重新加载</span></div>");
            this.loadDeptError.bind("click", function (e) {
                _this.loadDeptError.addClass("displaynone");
                _this.getDepartData();
            });
            this.departWrap.append(this.loadDeptError);
        }
        this.loadDeptError.removeClass("displaynone");
    };


    Component.prototype.initViewPagers = function (bottomWrap) {
        var _this = this;
        this.departWrap = $("<div class='dp-ps-vp-dept'></div>");
        this.departWrapLoading = $("<div class='dp-ps-vp-dept-loading displaynone'></div>");
        this.departWrapLoading.spin('tiny', '#999');
        this.departWrap.append(this.departWrapLoading);
        this.leftTree = new leftTree({selector: this});

        this.departWrap.append(this.leftTree.$el);
        this.personWrap = $("<div class='dp-ps-vp-person displaynone'></div>");
        this.personList = new PersonList({selector: this});

        var leftTop = $("<div class='ds-ps-lefttop'></div>");
        var searchInput = $("<input placeholder='请输入人员名称进行搜索' type='text'/>");
        leftTop.append(searchInput);
        this.personWrap.append(leftTop).append(this.personList.$el);

        _this.timeid = null;
        searchInput.bind("keyup", function (e) {
            var keyword = e.target.value;
            if (_this.timeid) {
                window.clearTimeout(_this.timeid);
                _this.timeid = null;
            }
            _this.timeid = window.setTimeout(function () {
                _this.search(keyword);
            }, 600);
        });


        this.teamWrap = $("<div style='overflow:auto' class='dp-ps-vp-person displaynone'></div>");
        this.teamList = new TeamList({selector: this, pageview: this.pageview});
        this.teamWrap.append(this.teamList.$el);

        bottomWrap.append(this.departWrap).append(this.personWrap).append(this.teamWrap);

    };
    Component.prototype.search = function (keyword) {
        var _this = this;
        this.personList.loadFirstPageData(keyword, function () {
            _this.timeid = null;
        }, function () {
            _this.timeid = null;
        });
    };

    Component.prototype.show = function (selectedData) {
        var _this = this;
        this.getDepartData();

        this.setSelected(selectedData);
        this.bk.removeClass("displaynone");
        this.outWrap.removeClass("displaynone");
        if (this.config.mod === 3) {
            _this.segementChange(_this.personSegmentItem, 2);
        }
    };

    Component.prototype.hide = function () {
        this.bk.addClass("displaynone");
        this.outWrap.addClass("displaynone");
    };

    Component.prototype.setTitle = function (titleName) {
        var name = titleName ? titleName : "";
        this.title.text(name);
    };

    return Component;
});
